package game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

public class HexBoardPanel extends JPanel implements MouseMotionListener {

	private static final long serialVersionUID = 1L;

	public final int size;
	private final HexBoard hexBoard;
	
	// This is used to determine whether to highlight the cell the cursor is over.
	// If the game is over (the nextMoveBtn is not enabled) don't show it.
	public final JButton nextMoveBtn;
	
	private Cell mouseCell;

	
	public final HexBoardImage hexBoardImage;

	private int panelWidth = -1;

	private int panelHeight = -1;

	public HexBoardPanel(HexBoard hexBoard, JButton nextMoveBtn) {
		this.hexBoard = hexBoard ;
		this.size = hexBoard.getSize();
		
		this.nextMoveBtn = nextMoveBtn;

		this.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED,
            hexBoard.getPlayer(1).getColor(), 
            hexBoard.getPlayer(2).getColor(),
            Color.DARK_GRAY,
            Color.BLACK));
		this.setBackground(Color.WHITE); // Sets background color
		this.hexBoardImage = new HexBoardImage(this, hexBoard);
		
		hexBoard.setHexBoardImage(this.hexBoardImage);
	}


  public Cell cellThatContainsPoint(Point p) {
    for (int y = 0; y < size; y++) {
      for (int x = 0; x < size; x++) {
        if (hexBoardImage.hexes[x][y].contains(p)) return hexBoard.getCell(x, y);
      }
    }
    return null;
  }


  @Override
  public void mouseDragged(MouseEvent e) { /* */ }


  @Override
  public void mouseMoved(MouseEvent e) {
    if (! nextMoveBtn.isEnabled()) return;
    Point mousePoint = new Point(e.getX(), e.getY());
    Cell newMouseCell = cellThatContainsPoint(mousePoint);
    if (mouseCell == newMouseCell) return;
    mouseCell = newMouseCell;
    hexBoardImage.highlightMouseCellBorder(mouseCell);
    repaint();
  }


  @Override
  public void paintComponent(Graphics g) {
	  if (sizeChanged() && hexBoardImage.initialized) {
		  hexBoardImage.initializeImage();   
	  }
	  super.paintComponent(g); 
	  g.drawImage(hexBoardImage.imageBuffer, 0, 0, null);   
  }


  private boolean sizeChanged() {
	  int pWidth  = getWidth();
	  int pHeight = getHeight();
	  if (pWidth == panelWidth && pHeight == panelHeight)
		  return false;
	  panelWidth  = pWidth;
	  panelHeight = pHeight;
	  return true;
  }


}
